/**
 * 
 */
package cc.rico.shiro.filter;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.AccessControlFilter;
import org.apache.shiro.web.util.WebUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 自定义AccessControlFilter过滤器
 * @author JiWo 2016年6月23日
 *
 */
public class CustomAccessControlFilter extends AccessControlFilter {
	private static final Logger logger = LoggerFactory.getLogger(CustomAccessControlFilter.class);

	private static List<String> permissionsList = new ArrayList<String>();
	
	static {
		permissionsList.add("/home/add");
		permissionsList.add("/home/delete");
		permissionsList.add("/home/update");
		permissionsList.add("/home/find");
	}
	
	/* (non-Javadoc)
	 * @see org.apache.shiro.web.filter.AccessControlFilter#isAccessAllowed(javax.servlet.ServletRequest, javax.servlet.ServletResponse, java.lang.Object)
	 */
	@Override
	protected boolean isAccessAllowed(ServletRequest req, ServletResponse resp, Object mappedValue) throws Exception {
		logger.info("mappedValue = {}", mappedValue);
		
		Subject currentUser = SecurityUtils.getSubject();
		if(!currentUser.isAuthenticated()) {
			logger.info("user[name={}] is not authenticated...", currentUser.getPrincipal());
			WebUtils.issueRedirect(req, resp, "/login.html");
		}
		
		HttpServletRequest request = WebUtils.toHttp(req);
		//HttpServletResponse response = WebUtils.toHttp(resp);
		
		String uri = request.getRequestURI().replace(".html", "");
		logger.info("##isAccessAllowed.uri={}", uri);
		
		if(!permissionsList.contains(uri)) {
			logger.info("###issueRedirect, url={}", uri);
			WebUtils.issueRedirect(req, resp, "/login.html");
		}
		
		return true;
	}

	/* (non-Javadoc)
	 * @see org.apache.shiro.web.filter.AccessControlFilter#onAccessDenied(javax.servlet.ServletRequest, javax.servlet.ServletResponse)
	 */
	@Override
	protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {
		logger.info("##CustomAccessControlFilter.onAccessDenied");
		WebUtils.redirectToSavedRequest(request, response, this.getLoginUrl());
		
		return true;
	}

}
